package com.lw.smartdevice.events.listeners;

import com.lw.smartdevice.events.DevicePowerEvent;
import com.lw.smartdevice.pojo.SysDevice;
import com.lw.smartdevice.service.SysDeviceService;
import com.lw.smartdevice.utils.RequestUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.event.EventListener;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

import java.util.Date;

/**
 * @author Administrator
 * @version 1.0
 * @description:
 * @date 2022/3/24 22:54
 */
@Component
public class DevicePowerListener {

    private SysDeviceService sysDeviceService;

    @Autowired
    public void setSysDeviceService(SysDeviceService sysDeviceService) {
        this.sysDeviceService = sysDeviceService;
    }

    @EventListener
    @Async
    public void onEvent(DevicePowerEvent event){
        String deviceId = event.getDeviceId();
        String ip = event.getIp();
        String location = RequestUtil.getLocationByIp(ip);//获取地区
        SysDevice sysDevice=new SysDevice();
        sysDevice.setDeviceId(deviceId);
        switch (event.getDeviceStatus()){
            case ONLINE:
                sysDevice.setConnectTime(new Date());
                sysDevice.setCurrentConnectIp(ip);
                sysDevice.setConnectLocation(location);
                sysDevice.setIsOnline(1L);
                break;
            case OFFLINE:
                sysDevice.setLostConnectTime(new Date());
                sysDevice.setIsOnline(2L);//设为离线
        }


        sysDeviceService.updateById(sysDevice);
    }
}
